package com.cskaoyan.mall.service;

import com.cskaoyan.mall.bean.Brand;
import com.cskaoyan.mall.bean.bo.BrandListBO;
import com.cskaoyan.mall.bean.bo.BrandUpdateBO;
import com.cskaoyan.mall.bean.vo.GeneralItemsBean;
import com.cskaoyan.mall.bean.vo.GoodsBrandVO;
import com.cskaoyan.mall.mapper.BrandMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author: dyj
 * @Date: 2021/1/9 17:09
 * @Description
 */
@Service
public class BrandServiceImpl implements BrandService {

    @Autowired
    BrandMapper brandMapper;

    @Override
    public GeneralItemsBean<Brand> queryList(BrandListBO brandListBO) {

        // 分页处理
        PageHelper.startPage(brandListBO.getPage(),brandListBO.getLimit());

        // 查询制造商信息，  id name 为可选条件
        List<Brand> brandList = brandMapper.selectBrandList(brandListBO);

        // 获取总数目
        PageInfo<Brand> brandPageInfo = new PageInfo<>(brandList);

        int total = (int) brandPageInfo.getTotal();

        return GeneralItemsBean.data(brandList,total);
    }

    @Override
    public void insertBrand(Brand brand) {

        // 设置添加时间和更新时间
        Date date = new Date();
        String nowtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
        brand.setAddTime(nowtime);
        brand.setUpdateTime(nowtime);

        // 插入 使用useGenerateKeys
        brandMapper.insertSelective(brand);
    }

    @Transactional
    @Override
    public Brand updateBrand(BrandUpdateBO brandUpdateBO) {

        // 设置更新时间
        Brand brand = new Brand(brandUpdateBO);
        Date date = new Date();
        String nowtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
        brand.setUpdateTime(nowtime);

        // 更新
        brandMapper.updateByPrimaryKeySelective(brand);

        // 返回更新的品牌制造商信息
        return brand;
    }

    @Override
    public int deleteBrand(Brand brand) {
        int rows = brandMapper.deleteByPrimaryKey(brand.getId());
        return rows;
    }

    @Override
    public List<GoodsBrandVO> queryAllGoodsBrands() {
        List<GoodsBrandVO> goodsBrandVOS = brandMapper.selectGoodsAllBrands();
        return goodsBrandVOS;
    }
}
